#include "phonepwdloginwidget.h"

#include <QEvent>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QRegularExpressionValidator>
#include <QSslConfiguration>
#include <QTextEdit>
#include <QToolTip>
#include "Functionality/loginfactory.h"
#include "Functionality/loginfunctionality.h"
#include "loginWidget/registerDialog.h"
#include "utils/signalcenter.h"
#include "utils/util.h"
#include <socketFacotry/sslsocketfactory.h>
#include <utils/keymanager.h>

phonePwdLoginWidget::phonePwdLoginWidget(QWidget *parent)
    : QWidget{parent}
    , mainVLayout(new QVBoxLayout(this))
    , verificationCodeLogin(new HoverToolButton())
    , phoneNumberInput(false)
    , passwdInput(false)
{
    mainVLayout->setSpacing(30);

    addSpaceLabel(300, 15);
    QHBoxLayout *hLayout = new QHBoxLayout();
    hLayout->setSpacing(110);
    hLayout->setAlignment(Qt::AlignLeft);
    hLayout->setObjectName("hLayout");

    QLabel *pwdTipLabel = new QLabel();
    setLable(pwdTipLabel, "pwdTipLabel", "手机密码登录", "Microsoft YaHei", 16);
    pwdTipLabel->setStyleSheet("QLabel{color:black;}");
    hLayout->addWidget(pwdTipLabel);
    verificationCodeLogin->setObjectName("verificationCodeLogin");
    hLayout->addWidget(verificationCodeLogin);
    mainVLayout->addLayout(hLayout);

    addPhoneNumberLayout();
    addPasswdLayout();
    addLoginBtn();
    addRemeberAndRegisteLayout();
    addSpaceLabel(300, 230);
    factory = std::make_shared<loginFactory>(); //初始化的顺序不一样，应该等到后面去创建
    Functionality = factory->create(); //创建了这个后，module初始化和连接就已经发起了的
    //绑定信号和槽
    bindConnect();
}

void phonePwdLoginWidget::onLoginBtnClicked()
{
    QString phoneNumber = phoneNumberlineEditor->text();
    QString passwd = passwdLineEditor->text();

    if (!isValidPhoneNumber(phoneNumber)) {
        QRect rect = loginBtn->rect();
        QToolTip::showText(phoneNumberlineEditor->mapToGlobal(QPoint(0, 5)),
                           "手机号格式不正确",
                           phoneNumberlineEditor,
                           rect);
        return;
    }
    auto lf = dynamic_cast<loginFunctionality *>(Functionality.get());
    lf->setParameters(phoneNumber, passwd);
    Functionality->executeFunction();
    // videoClient.sendData(phoneNumber.toLatin1());
}

void phonePwdLoginWidget::onRegisterClicked()
{
    //创建一个窗口
    registerDialog registerDialog;
    QPalette palette = registerDialog.palette();
    palette.setColor(QPalette::Window, Qt::white);

    //应用调色板
    registerDialog.setAutoFillBackground(true); //设置自动填充背景颜色
    //设置填充的颜色根据调色板
    registerDialog.setPalette(palette);
    registerDialog.exec();
}

void phonePwdLoginWidget::onLoginSuccessed(QString data)
{
    QMessageBox::information(this, "提示", data);
    emit SIGNALCENTER.loginSuccessed();
}

void phonePwdLoginWidget::onLoginFailed(QString data)
{
    QMessageBox::critical(this, "错误", data, QMessageBox::Close);
    phoneNumberlineEditor->clear();
    passwdLineEditor->clear();
}

void phonePwdLoginWidget::addPhoneNumberLayout()
{
    QVBoxLayout *VLayout = new QVBoxLayout();
    VLayout->setSpacing(10);

    QHBoxLayout *HLayout = new QHBoxLayout();
    HLayout->setObjectName("HLayout");
    HLayout->setAlignment(Qt::AlignLeft);
    QLabel *labelPhone = new QLabel();
    setLable(labelPhone, "labelPhone", "手机号码", "Microsoft YaHei", 12);
    labelPhone->setStyleSheet("QLabel{color:black;}");
    HLayout->addWidget(labelPhone);
    VLayout->addLayout(HLayout);

    QHBoxLayout *HLayout2 = new QHBoxLayout();
    HLayout2->setAlignment(Qt::AlignLeft);
    HLayout2->setObjectName("HLayout2");
    HLayout2->setSpacing(6);
    QLabel *labelPhoneHeader = new QLabel();
    setLable(labelPhoneHeader, "labelPhoneHeader", "+86", "Microsoft YaHei", 10);
    HLayout2->addWidget(labelPhoneHeader);

    //这是设置竖线
    QFrame *line = new QFrame();
    line->setObjectName("line");
    line->setFrameShape(QFrame::VLine);
    line->setFrameShadow(QFrame::Raised);
    HLayout2->addWidget(line);

    //设置文本输入框
    phoneNumberlineEditor = new QLineEdit();
    phoneNumberlineEditor->setObjectName("phoneNumberlineEditor");
    phoneNumberlineEditor->setPlaceholderText("请输入手机号");
    phoneNumberlineEditor->setStyleSheet(
        "QLineEdit{border:none;border-bottom: 1px solid "
        "#cccccc;}QLineEdit:focus{border-bottom: 1px solid #0078d7;}");
    //安装输入验证器，使用正则表达式
    QRegularExpression regExp("^[0-9]+$");
    QRegularExpressionValidator *validator = new QRegularExpressionValidator(regExp, this);
    phoneNumberlineEditor->setValidator(validator);
    HLayout2->addWidget(phoneNumberlineEditor);

    VLayout->addLayout(HLayout2);
    mainVLayout->addLayout(VLayout);
}

void phonePwdLoginWidget::addPasswdLayout()
{
    QVBoxLayout *VLayout = new QVBoxLayout();
    VLayout->setSpacing(10);

    QHBoxLayout *HLayout = new QHBoxLayout();
    HLayout->setObjectName("HLayout");
    HLayout->setAlignment(Qt::AlignLeft);
    QLabel *labelPhone = new QLabel();
    setLable(labelPhone, "labelPhone", "密码", "Microsoft YaHei", 12);
    labelPhone->setStyleSheet("QLabel{color:black;}");
    HLayout->addWidget(labelPhone);
    VLayout->addLayout(HLayout);

    QHBoxLayout *HLayout2 = new QHBoxLayout();
    HLayout2->setAlignment(Qt::AlignLeft);
    HLayout2->setObjectName("HLayout2");
    HLayout2->setSpacing(6);
    passwdLineEditor = new QLineEdit();
    passwdLineEditor->setObjectName("passwdLineEditor");
    passwdLineEditor->setPlaceholderText("请输入密码");
    passwdLineEditor->setStyleSheet("QLineEdit{border:none;border-bottom: 1px solid "
                                    "#cccccc;}QLineEdit:focus{border-bottom: 1px solid #0078d7;}");
    //输入密码的需要设置回显模式
    passwdLineEditor->setEchoMode(QLineEdit::Password);

    HLayout2->addWidget(passwdLineEditor);

    //添加忘记密码的按钮
    forgetPasswdBtn = new QPushButton();
    forgetPasswdBtn->setObjectName("forgetPasswdBtn");
    forgetPasswdBtn->setText("忘记密码?");
    QFont font = forgetPasswdBtn->font();
    setQFont(font, "Microsoft YaHei", 10, false);
    forgetPasswdBtn->setFont(font);
    forgetPasswdBtn->setStyleSheet("QPushButton{border:none;}");
    forgetPasswdBtn->installEventFilter(this);
    HLayout2->addWidget(forgetPasswdBtn);
    VLayout->addLayout(HLayout2);
    mainVLayout->addLayout(VLayout);
}

void phonePwdLoginWidget::addSpaceLabel(int width, int height)
{
    QLabel *space = new QLabel();
    space->setMinimumSize(QSize(width, height));
    space->setMaximumSize(QSize(width, height));

    mainVLayout->addWidget(space);
}

bool phonePwdLoginWidget::eventFilter(QObject *watch, QEvent *event)
{
    if (watch->objectName() == "forgetPasswdBtn") {
        if (event->type() == QEvent::Enter) {
            forgetPasswdBtn->setStyleSheet("QPushButton{border:none;color:#2F95D5;}");
        } else if (event->type() == QEvent::Leave) {
            forgetPasswdBtn->setStyleSheet("QPushButton{border:none;}");
        }
    } else if (watch->objectName() == "registrationBtn") {
        if (event->type() == QEvent::Enter) {
            registrationBtn->setStyleSheet("QPushButton{border:none;color:#2F95D5;}");
        } else if (event->type() == QEvent::Leave) {
            registrationBtn->setStyleSheet("QPushButton{border:none;}");
        }
    }
    return QObject::eventFilter(watch, event);
}

void phonePwdLoginWidget::addLoginBtn()
{
    loginBtn = new QPushButton();
    setPushBtn(loginBtn,
               "loginBtn",
               QSize(360, 50),
               "",
               "border: none;",
               true,
               ":/resources/login2.png");
    loginBtn->setEnabled(false);
    mainVLayout->addWidget(loginBtn);
}

void phonePwdLoginWidget::addRemeberAndRegisteLayout()
{
    QHBoxLayout *HLayout = new QHBoxLayout();
    HLayout->setAlignment(Qt::AlignLeft);
    HLayout->setSpacing(200);
    rememberPaawdBox = new QCheckBox();
    rememberPaawdBox->setObjectName("rememberPaawdBox");
    rememberPaawdBox->setText("记住密码");
    QFont font = rememberPaawdBox->font();
    setQFont(font, "Microsoft YaHei", 10, false);
    rememberPaawdBox->setFont(font);
    HLayout->addWidget(rememberPaawdBox);

    registrationBtn = new QPushButton();
    registrationBtn->setObjectName("registrationBtn");
    registrationBtn->setText("新用户注册");
    QFont font2 = registrationBtn->font();
    setQFont(font2, "Microsoft YaHei", 11, false);
    registrationBtn->setFont(font2);
    registrationBtn->setStyleSheet("QPushButton{border:none;}");
    //安装事件过滤器
    registrationBtn->installEventFilter(this);
    HLayout->addWidget(registrationBtn);
    mainVLayout->addLayout(HLayout);
}

void phonePwdLoginWidget::bindConnect()
{
    connect(phoneNumberlineEditor, &QLineEdit::textEdited, [&](const QString &text) {
        if (!text.isEmpty()) {
            phoneNumberInput = true;
        } else {
            phoneNumberInput = false;
            loginBtn->setEnabled(false);
        }

        if (phoneNumberInput && passwdInput) {
            loginBtn->setIcon(QIcon(":/resources/login.png"));
            loginBtn->setEnabled(true);
        }
    });

    connect(passwdLineEditor, &QLineEdit::textEdited, [&](const QString &text) {
        if (!text.isEmpty()) {
            passwdInput = true;
        } else {
            passwdInput = false;
            loginBtn->setEnabled(false);
        }

        if (phoneNumberInput && passwdInput) {
            loginBtn->setIcon(QIcon(":/resources/login.png"));
            loginBtn->setEnabled(true);
        }
    });

    connect(loginBtn, &QPushButton::clicked, this, &phonePwdLoginWidget::onLoginBtnClicked);
    connect(registrationBtn, &QPushButton::clicked, this, &phonePwdLoginWidget::onRegisterClicked);
    auto lf = dynamic_cast<loginFunctionality *>(Functionality.get());
    connect(lf, &loginFunctionality::loginSuccessed, this, &phonePwdLoginWidget::onLoginSuccessed);
    connect(lf, &loginFunctionality::loginFailed, this, &phonePwdLoginWidget::onLoginFailed);
}

bool phonePwdLoginWidget::isValidPhoneNumber(const QString &phoneNumber)
{
    // 正则表达式：以1开头，第二位是3-9的数字，后面是9位数字，总共11位
    QRegularExpression regex("^1[3-9]\\d{9}$");
    return regex.match(phoneNumber).hasMatch();
}

void phonePwdLoginWidget::initSslSocket()
{
    // //配置ssl
    // QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
    // sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone); //不启动证书验证

    // //连接ssl服务器
}
